var grid=null;
var dlg=null;
$(document).ready(function(){
	var currWidth=$(document).width();
	dlg=$("#dlg").dialog({
		closed:true,
		cache:false,
		resizable:false,
		modal:true,
		buttons:[{
			text:"保存",
			iconCls:"icon-save",
			handler:function(){
				var url=base+"/user/";
				if(flg.val()=="1"){
					url+="save";
				}else{
					url+="update";
				}
				$("#frm").form("submit",{
					url:url,
					success:function(data){
						if(data){
							$("#frm").form("clear");
							dlg.dialog("refresh");
							dlg.dialog("close");
							grid.datagrid("reload");
						}else{
							parent.$.messager.alert("错误","保存失败！","error");
						}
					}
				});
			}
		},{
			text:"取消",
			iconCls:"icon-cancel",
			handler:function(){
				dlg.dialog("close");
				dlg.dialog("refresh");
			}
		}]
	});
	dlg.dialog("close");
	grid=$("#resultTable").treegrid({
		 height:$(document).height(),
		 url:base+rootPath+"/getData"+suffix,
		 idField:"id",
		 treeField:"text",
		 parentField:"fatherId",
		 fitColumns:false,
		 pagination:false,
		 animate: false,
		 collapsible: true,
		 border:true,
		 singleSelect:true,
		 rownumbers:false,
		 width:"auto",
		 height:"auto",
		 toolbar:toolbar,
		 columns:[[
		       {field:"id",title:"id",hidden:true,width:0},
		       {field:"text",title:"菜单名称",align:"left",width:currWidth*0.15},
		       {field:"fatherName ",title:"父菜单名称 ",align:"center",width:currWidth*0.1,formatter:function(value,row){return row.fatherName;}},
		       {field:"masterName ",title:"编码 ",align:"center",width:currWidth*0.1,formatter:function(value,row){return row.masterName;}},
		       {field:"iconCls ",title:"菜单图标 ",align:"center",width:currWidth*0.05,
	            	  formatter:function(value,row){
	            		  return "<span class='"+row.iconCls+"' style='display:inline-block;vertical-align:middle;width:16px;height:16px;'></span>";
						}},
		       {field:"url ",title:"访问路径 ",align:"center",width:currWidth*0.1,
					  formatter:function(value,row){
						return row.url;
					  }
				},
		       {field:"type ",title:"类型 ",align:"center",width:currWidth*0.05,
		    	   formatter:function(value,row){
         		  if("F"==row.type){
         			  return "<font color='green'>菜单<font>";
         		  }
          		  else{
          			  return "<font color='red'>操作<font>";
          		  }
				}},
		       {field:"used ",title:"启用 ",align:"center",width:currWidth*0.05,
					formatter:function(value,row){
	         		  if(1==row.used){
	         			  return "<font color='green'>是<font>";
	         		  }
	          		  else{
	          			  return "<font color='red'>否<font>";
	          		  }
					}
				},
			   {field:"child",title:"根菜单",align:"center",width:currWidth*0.05,
					formatter:function(value,row){
						if(row.type=="F"){
							if(1==row.child){
								return "<font color='green'>是<font>";							
							}else{
								return "<font color='red'>否<font>";								
							}
						}else{
							return "";
						}
					}
				},
			   {field:"position",title:"显示位置",align:"center",width:currWidth*0.05,formatter:function(value,row){
				   var positions=row.position;
				   var result="";
				   if(positions!=undefined){
					   positions=positions.replace("[","").replace("]","").replace(" ","");
					   var positionArr=positions.split(",");
					   for(var i=0,len=positionArr.length;i<len;i++){
						   result+=positionArr[i]=="top"?"顶部/":"行中/";
					   }
					   result=result.substring(0,result.length-1);
				   }
				   return result;
			   }},
			   {field:"seq",title:"排序序号",align:"center",width:currWidth*0.05},
		       {field:"createTime",title:"创建日期",align:"center",width:currWidth*0.12},
		       {field:"description ",title:"菜单描述 ",align:"center",width:currWidth*0.1,formatter:formatDescr}
		 ]] 
	});
});

function initDialog(){
	//父级菜单
	var menuTree=null;
	var i=0;
	menuTree=$("#fatherId").combotree({
		width:171,
		url:base+"/power/getPowerEdit"+suffix,
		idField:"id",
		textFiled:"powerName",
		parentField:"fatherId",
	 	editable:false,
	 	panelHeight:"auto",
	 	onLoadSuccess:function(node,data){
	 		if($("#pId").val()!=null){
	 			menuTree.combotree("setValue",$("#pId").val());
	 			var t=menuTree.combotree("tree");
	 			var pNode = t.tree("find",$("#pId").val());
	 			$("#url").validatebox({required:true});
	 			if(pNode!=null){
	 				if(pNode.attributes.child){
	 					$("#type").combobox("select","O");
	 				}
	 				var parentNode=t.tree("getParent",pNode.target);
	 				while(parentNode!=null){
	 					t.tree("expand",parentNode.target);
	 					parentNode=t.tree("getParent",parentNode.target);
	 				}
	 			}
	 		}
	 	},
	 	onChange:function(newValue, oldValue){
	 		var t = $(this).combotree("tree");	// 获取树对象
	 		var node = t.tree("getSelected");		// 获取选择的节点
	 		if(i>0){
	 			if(node.attributes.child){
	 				$("#type").combobox("setValue","O");
	 			}else{
	 				$("#type").combobox("setValue","F");
	 			}
	 		}
	 		i++;
	 	},
	 	loadFilter:	function(data, parent){
	 		var opt = $(this).data().tree.options;
	 		var idFiled,textFiled,parentField;
	 		if (opt.parentField) {
	 			idFiled = opt.idFiled || "id";
	 			textFiled = opt.textFiled || "powerName";
	 			parentField = opt.parentField || "fatherId";
	 			
	 			var i,l,treeData = [],tmpMap = [];
	 			var attribute=null;
	 			for (i = 0, l = data.length; i < l; i++) {
	 				tmpMap[data[i][idFiled]] = data[i];
	 			}
	 			
	 			for (i = 0, l = data.length; i < l; i++) {
	 				data[i].state=data[i].status;
	 				data[i].targets=data[i].target;
	 				
	 				attribute={};
	 				attribute.url=data[i].url;
	 				attribute.type=data[i].type;
	 				attribute.child=data[i].child;
	 				attribute.masterName=data[i].masterName;
	 				data[i].attributes=attribute;
	 				
	 				if(data[i].type=="F" && data[i].child==1){
	 					data[i].state="open";
	 				}
	 				
	 				if (tmpMap[data[i][parentField]] && data[i][idFiled] != data[i][parentField]) {
	 					if (!tmpMap[data[i][parentField]]["children"])
	 						tmpMap[data[i][parentField]]["children"] = [];
	 					data[i]["text"] = data[i][textFiled];
	 					tmpMap[data[i][parentField]]["children"].push(data[i]);
	 				} else {
	 					data[i]["text"] = data[i][textFiled];
	 					treeData.push(data[i]);
	 				}
	 			}
	 			return treeData;
	 		}
	 		return data;
	 	}
	});
	//清空父类tree选中项
	$("#clear").click(function(){
		$("#fatherId").combotree("clear");
	});

	//是否根菜单
	$("input[name='child'][type='radio']").change(function(){
		if($(this).val()=="0"){
			$("#url").validatebox("disableValidation");
			$("#url").attr("disabled",true);
		}else{
			$("#url").validatebox("enableValidation");
			$("#url").attr("disabled",false);
		}
	});
	//图标下拉菜单
	$("#iconCls").combobox({
		width:171,
		data:my.iconData,
		editable:false,
		valueField:"value",    
	    textField:"text",
		formatter: function(v){
			return "<span class='"+v.value+"' style='display:inline-block;vertical-align:middle;width:16px;height:16px;'></span>"+v.value;
		}
	});
	/**
	 * 类型变动事件
	 */
	$("#type").combobox({
		onChange:function(newValue, oldValue){
			var childs=$("input[name='child']");
			$(childs.get(0)).attr("checked",true);
			if(newValue=="O"){
				$(".hide").hide();
				$("input[name='child']").attr("disabled",true);
				$(".position").show();
				$("#position").attr("disabled",false);
			}else{
				$(".position").hide();
				$("#position").attr("disabled",true);
				$(".hide").show();
				$("input[name='child']").attr("disabled",false);
			}
		}
	});
}

/**
 * 添加菜单
 */
function toMyAdd(){
	dlg.dialog({title:"添加"});
	dlg.dialog("refresh");
	$("#frm").form("reset");
	dlg.dialog("center");
	parent.$(dlg).dialog("open");
	initDialog();
	/*
	var addDialog=null;
	var url=base+"/power/toAdd"+suffix;
	var row=grid.treegrid("getSelected");
	if(row!=null){
		if(row.type!="F"){
			parent.$.messager.alert("提示","只允许选择菜单类型添加!","info");
			return;
		}
		url=url+"?fatherId="+row.id;
	}
	addDialog=parent.my.modalDialog({
			title : "添加菜单",
			width : 620,
			height : 400,
			url:url,
			buttons : [ {
				text : "保存",
				iconCls : "icon-ok",
				handler : function() {
					addDialog.find("iframe").get(0).contentWindow.submitForm(addDialog,grid,parent.$);
				}
			}, {
				text : "取消",
				iconCls : "icon-cancel",
				handler : function() {
					addDialog.dialog("destroy");
				}
			}
			]
		});
	*/
}
/**
 * 删除菜单
 * */
function delMySelected(){
	var row = grid.treegrid("getSelected");
	var url=base+"/power";
	if(row!=null){
		parent.$.messager.confirm("确认","您确认要删除记录吗？",function(r){
			if(r){
				$.post(url+"/checkPower/"+row.id+suffix+"?_d="+new Date().toTimeString(),function(data){
					if(data){
						parent.$.messager.alert("提示","该菜单下有子菜单,请先删除子菜单","info");
					}else{
						$.post(url+"/rem/"+row.id+suffix+"?_d="+new Date().toTimeString(),function(data){
							if(data){
								parent.$.messager.alert("提示", "删除成功！", "info");
								grid.treegrid("reload");
							}
						},"json");
					}
				},"json");
			}
		});
	}else{
		parent.$.messager.alert("提示","请选择一行记录!","info");
	}
}